import {Component, OnInit, ViewChild} from '@angular/core';
import {HttpService} from '../../lib/service/http.service';
import {ModalDirective} from 'ngx-bootstrap';
import {adSystemApiUrl, AliyunOssOutputUrl} from '../../../config/api';
import {AddBase, EditBase} from '../main';
import {Router} from '@angular/router';
import {AdOssUploadService} from '../../lib/service/ad-oss-upload.service';
import {LocalStorageService} from '../../lib/service/local-storage.service';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss'],
  providers: [HttpService, LocalStorageService]
})
export class IndexComponent implements OnInit {

  modelCase;
  myAppletList: any;
  appletList: any;
  operate_uuid: string;  // 操作的小程序applet_uuid
  aliyunOssOutputUrl: string = AliyunOssOutputUrl;
  addBase = new AddBase;
  editBase = new EditBase;
  template_categoryID: number;
  hasChoseTem = true;
  hasUpload = true;  // 是否已经上传logo
  canClick = true;  // 是否允许点击

  img_file: string;
  img_name: string;
  img_url: string;

  type: string;
  message: string;
  isShow = false;

  totalItems: number;
  itemsPerPage = 4;
  currentPage = 1;


  @ViewChild('pickModal') public pickModal: ModalDirective;
  @ViewChild('editModal') public editModal: ModalDirective;
  @ViewChild('delModal') public delModal: ModalDirective;

  constructor(private httpService: HttpService,
              private route: Router,
              private adOssUploadService: AdOssUploadService,
              private localStorageService: LocalStorageService) {
  }

  ngOnInit() {
    this.getAppletList();
    this.localStorageService.clearNowAppleto();
    this.localStorageService.clearAppletToken();
    localStorage.removeItem('baseInfo');
  }

  // 获取我的小程序列表
  getAppletList() {
    const id = this.localStorageService.getUserInfo().id;
    const url = `${adSystemApiUrl}/v1/member/applets/list?userID=${id}`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.myAppletList = res.data.data;
      }
    );
  }

  // 删除小程序
  delApplet(applet_uuid: string) {
    this.operate_uuid = applet_uuid;
    this.delModal.show();
  }
  delAppletSubmit() {
    const url = `${adSystemApiUrl}/v1/member/applets/del_base`,
          data = {applet_uuid: this.operate_uuid};
    return this.httpService.httpPostAuth(url, data).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '删除成功';
          this.isShow = true;
          this.delModal.hide();
          this.getAppletList();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 上传图片
  uploadImg($event: any, imgName: string) {
    this.hasUpload = true;
    const file = $event.path[0].files[0];
    const myReader = new FileReader();
    const self = this;
    const suffix = file.name.replace(/.+\./, '').toLowerCase();
    this.img_file = file;
    const now = new Date();
    this.img_name = now.getTime() + imgName + '.' + suffix;
    myReader.readAsDataURL(file);
    myReader.onloadend = function (e) {
      self.img_url = myReader.result;
    };
  }

  // 获取小程序模板列表
  getAppletTempList(page) {
    const url = `${adSystemApiUrl}/v1/member/template/list?page=${page}&pageSize=${this.itemsPerPage}`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.totalItems = res.data.total;
        this.currentPage = res.data.current_page;
        this.appletList = res.data.data;
      }
    );
  }

  // 添加小程序
  addApplet() {
    this.getAppletTempList(1);
    this.pickModal.show();
    this.canClick = true;
  }

  // 选择模板
  choseTem(templateID: number, template_categoryID: number) {
    this.hasChoseTem = true;
    this.addBase.templateID = templateID;
    this.addBase.template_categoryID = template_categoryID;
  }

  // 编辑小程序
  edit(id: number) {
    this.getAppletTempList(1);
    const url = `${adSystemApiUrl}/v1/member/applets/detail?id=${id}`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        if (res.code === 2000) {
          this.editBase.applet_uuid = res.data.applet_uuid;
          this.editBase.title = res.data.title;
          this.editBase.template_id = res.data.template_id;
          this.editBase.logo = res.data.logo;
          this.img_url = this.aliyunOssOutputUrl + '/' + res.data.logo;
          this.editModal.show();
        } else {
          this.isShow = true;
          this.message = res.message;
          this.type = 'error';
        }
      }
    );
  }

  // 编辑小程序提交
  editAppletSubmit() {
    this.canClick = false;
    const url = `${adSystemApiUrl}/v1/member/applets/mod_base`;
    return this.httpService.httpPostAuth(url, this.editBase).subscribe(
      res => {
        if (res.code === 2000) {
          this.adOssUploadService.getSignature('/v1/member/account/' + res.data.user_id + '/' + res.data.id + '?callback=true').subscribe(
            res1 => {
              this.adOssUploadService.fileUpload(this.img_file, res1.data, this.img_name, 'logo').subscribe(
                res2 => {
                  if (res2.status === 200) {
                    this.canClick = true;
                    this.editModal.hide();
                    this.getAppletList();
                    this.isShow = true;
                    this.message = '修改成功';
                    this.type = 'success';
                  } else {
                    this.canClick = true;
                    this.type = 'error';
                    this.message = '图片上传失败';
                    this.isShow = true;
                  }
                }
              );
            });
        } else {
          this.canClick = true;
          this.isShow = true;
          this.message = res.message;
          this.type = 'error';
        }
      }
    );
  }

  // 管理小程序
  manege(item) {
    // 设置当前小程序信息
    this.localStorageService.setNowApplet(item);
    if (item.status === '已发布') {
      this.route.navigate(['/member/product/list']);
    } else {
      this.route.navigate(['/main/applet-setting/authorization']);
    }
  }

  // 新建小程序
  turnPage() {
    if (!this.addBase.templateID) {
      this.hasChoseTem = false;
      return;
    }
    if (!this.img_name) {
      this.hasUpload = false;
      return;
    }
    this.canClick = false;
    const userInfo = this.localStorageService.getUserInfo();
    this.addBase.userID = userInfo.id;
    this.addBase.userUUID = userInfo.user_uuid;
    this.addBase.logo = this.img_name;
    const url = `${adSystemApiUrl}/v1/member/applets/add_applet`;
    return this.httpService.httpPostAuth(url, this.addBase).subscribe(
      res => {
        this.canClick = true;
        if (res.code === 2000) {
          this.adOssUploadService.getSignature('/v1/member/account/' + this.addBase.userID + '/' + res.data.id + '?callback=true').subscribe(
            res1 => {
              this.adOssUploadService.fileUpload(this.img_file, res1.data, this.img_name, 'logo').subscribe(
                res2 => {
                  if (res2.status === 200) {
                    this.type = 'success';
                    this.message = '保存成功';
                    this.isShow = true;
                    this.localStorageService.setNowApplet(res.data);
                    this.route.navigate([`/main/applet-setting/authorization`]);
                  } else {
                    this.type = 'error';
                    this.message = '图片上传失败';
                    this.isShow = true;
                  }
                }
              );
            }
          );
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }

      }
    );
    // console.log(this.addBase);
    // this.localStorageService.setNowApplet(JSON.stringify(this.addBase));
    // this.route.navigate(['/main/authorization']);
  }

  pageChanged(event) {
    window.scrollTo(0, 0);
    this.getAppletTempList(event.page);
  }
}
